//
//  UIImageView+cache.m
//  iLookForiPhone
//
//  Created by Yinghui Zhang on 6/6/12.
//  Copyright (c) 2012 LavaTech. All rights reserved.
//


#import "UIImageView+cache.h"
#import <objc/runtime.h>
#import "NSString+x.h"
#import "BKHttpRequestManager.h"

@interface UIImageView(_cache)
@end
@implementation UIImageView(_cache)


- (BKHttpResponseHandler *)responseHandler {
    return (BKHttpResponseHandler *)objc_getAssociatedObject(self, @selector(responseHandler));
}

- (void)setResponseHandler:(BKHttpResponseHandler *)responseHandler {
    objc_setAssociatedObject(self, @selector(responseHandler), responseHandler, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

@implementation UIImageView(cache)

+ (BKHttpRequestPool *)sharedRequestPool {

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
    return objc_getAssociatedObject(self, @selector(sharedRequestPool)) ?: [BKHttpRequestPool defaultPool];
#pragma clang diagnostic pop
}

+ (void)setSharedRequestPool:(BKHttpRequestPool *)requestPool {
    objc_setAssociatedObject(self, @selector(sharedRequestPool), requestPool, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (void)cancelRequest {
    [[[self class] sharedRequestPool] removeResponseHandler:self.responseHandler];
    [self setResponseHandler:nil];
}
- (void)setImageURLString:(NSString *)url placeholderImage:(UIImage *)placeholderImage withImageLoadedCallback:(void (^)(NSString *url, NSString *filePath, NSError *error))callback{
    //url为空
    if (!url || [url length] == 0) {
        [self cancelRequest];
        self.image = placeholderImage;
        return;
    }
    //url不变
    if ([url isEqualToString:self.responseHandler.sessionTask.originalRequest.URL.absoluteString]) {
        return;
    }
    [self cancelRequest];
    
    NSString *fp = nil;
    if ([url isURL]) {
        fp = getHttpRequestCacheFilePath([NSURL URLWithString:url]);
    }else{
        fp = url;
    }
    if ([fp fileExists]) {
        UIImage *img = [UIImage imageWithContentsOfFile:fp];
        if (img) {
            self.image = img;
            if (callback) {
                callback(url,fp,nil);
            }
            return;
        }
    }
    self.image = placeholderImage;
    BKHttpRequestManager *requestManager = [BKHttpRequestManager manager];
    requestManager.requestPool = [[self class] sharedRequestPool];
    id responseHandler = [requestManager
     download:url
     progress:nil
     success:^(id  _Nonnull task, NSURL *_Nullable fp) {
         if ( fp && [[fp path] fileExists]) {
             [self setImage:[UIImage imageWithContentsOfFile:[fp path]]];
         }
         if (callback) {
             callback(url, [fp path], nil);
         }
     }
     failure:^(id  _Nullable task, NSURL *_Nullable fp, NSError * _Nonnull error) {
         if ( fp && [[fp path] fileExists]) {
             [self setImage:[UIImage imageWithContentsOfFile:[fp path]]];
         }
         if (callback) {
             callback(url, [fp path], error);
         }
         
     }];
    [self setResponseHandler:responseHandler];
}
- (void)setImageURLString:(NSString *)url{
    [self setImageURLString:url placeholderImage:nil withImageLoadedCallback:nil];
}
- (void)setImageURLString:(NSString *)url placeholderImage:(UIImage *)placeholderImage{
    [self setImageURLString:url placeholderImage:placeholderImage withImageLoadedCallback:nil];
}

@end
